package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.reporsitory.IDestinationSearchRepository;
import cn.wolfcode.luowowo.search.service.IDestinationSearchService;
import cn.wolfcode.luowowo.search.templates.DestinationTemplate;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class DestinationSearchServiceImpl implements IDestinationSearchService{
    @Autowired
    private IDestinationSearchRepository dao;
    @Autowired
    private ElasticsearchTemplate template;
    @Autowired
    private TransportClient client;
    //创建索引
    public void createIndex() {
        template.createIndex(DestinationTemplate.class);
        template.putMapping(DestinationTemplate.class);
    }

    public void initData() {

    }

    public void save(DestinationTemplate tt) {
        dao.save(tt);
    }

    public DestinationTemplate queryDestByName(String name) {
        Iterable<DestinationTemplate> dests = dao.search(QueryBuilders.termQuery("name", name));
        ArrayList<DestinationTemplate> list = new ArrayList<>();
        dests.forEach(d ->{
            list.add(d);
        });
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }

    public List<DestinationTemplate> questDestByKeyWord(SearchQueryObject qo) {
        Iterable<DestinationTemplate> dests = dao.search(QueryBuilders.matchQuery("name", qo.getKeyword()));
        ArrayList<DestinationTemplate> list = new ArrayList<>();
        dests.forEach(d ->{
            list.add(d);
        });
        return list;
    }
}
